package com.artisan.app.filter;

import com.alibaba.fastjson.JSON;
import com.artisan.common.pojo.ApiRes;
import com.artisan.common.pojo.AppApiBaseModel;
import com.artisan.common.utils.DateTimeUtils;
import com.artisan.common.utils.Utils;
import com.artisan.medium.app.utils.TokenUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

public class TokenFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url=httpRequest.getRequestURI();
        url=url.substring(url.lastIndexOf("/")+1,url.length());
        Map params=request.getParameterMap();
        Iterator it = params.keySet().iterator();
        System.out.println(url);
        while(it.hasNext()){
            String paramName = (String) it.next();
            String paramValue = request.getParameter(paramName);
            //处理你得到的参数名与值
            System.out.println(paramName+"="+paramValue);
        }
        //判断是否需要验证Token
        if(url.equals("fAlipayResult")
                ){
            chain.doFilter(request,response);
        }else{
            //获取token参数
            String token=httpRequest.getParameter("token");
            if(null!=token&&!"".equals(token)){
                Map<String,Object> resultMap= TokenUtils.getTokenMap(token);
                if(resultMap==null){
                    //参数为空
                    response.setCharacterEncoding("utf-8");
                    AppApiBaseModel appApiBaseModel = Utils.dataIllegalError(new AppApiBaseModel(),new ApiRes());
                    response.getWriter().write(JSON.toJSONString(appApiBaseModel));
                }else{
                    if(!DateTimeUtils.afterDate(DateTimeUtils.strToDate(resultMap.get("data").toString(),"yyyy-MM-dd HH:mm:ss"),new Date())){
                        //参数为空
                        response.setCharacterEncoding("utf-8");
                        AppApiBaseModel appApiBaseModel = Utils.outTimeError(new AppApiBaseModel(),new ApiRes());
                        response.getWriter().write(JSON.toJSONString(appApiBaseModel));
                    }else{
                        chain.doFilter(request,response);
                    }

                }
            }else{
                //参数为空
                response.setCharacterEncoding("utf-8");
                AppApiBaseModel appApiBaseModel = Utils.dataIllegalError(new AppApiBaseModel(),new ApiRes());
                response.getWriter().write(JSON.toJSONString(appApiBaseModel));
            }
        }

    }

    public void destroy() {

    }



}
